<?php

namespace Zwwl2016\Cluster; 

class Cluster
{
    public $url = "";
    private $debug=true;

    function __construct($url)
    {
        $this->url = $url;
    }

    public function debug($isDebug)
    {
        $this->debug=$isDebug;
        return $this;
    }

    public static function Instance($url)
    {
        $cluster = new Cluster($url);
        return $cluster;
    }

    /**
     * @return ClusterScaffold 获取集群的结构生成器
     */
    public function scaffold()
    {
        return new ClusterScaffold($this);
    }

    /**
     * @return  ClusterServices 获取集群的服务组
     */
    public function services()
    {
        return new ClusterServices($this);
    }

    /**
     * @param $serviceKey 参数，通过XXServiceKeys.XX 进行赋值。
     * @return  ClusterService 获取指定key的服务
     */
    public function service($serviceKey)
    {
        return new ClusterService($this,$serviceKey);
    }

    public function readHandler(string  $key, array $val)
    {
        return $this->execute($key, "handler", $val, false);
    }

    public function executeHandler(string  $key, array $val)
    {
        $this->execute($key, "handler", $val, true);
    }

    /**
     * @param $key
     * @param $type
     * @param $val
     * @param $async
     * @return string 执行操作
     */
    public function execute($key, $type, $val, $async)
    {
        if(empty($val))
        {
            $val="{}";
        }
        else
        {
            $val=json_encode($val);
        }
        $data = [
            "type" => $type,
            "key" => $key,
            "async" => $async,
            "val" => $val
        ];
        $data = json_encode($data);
        if($this->debug) {
            echo "请求参数:" . $data . "\n";
        }
       // $headerArray = array("Content-type:application/json;charset='utf-8'", "Accept:application/json");
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $this->url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
       // curl_setopt($curl, CURLOPT_HTTPHEADER, $headerArray);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        $json=json_decode($output,true);
        curl_close($curl);
        $val=json_decode($json['val'],true);
        return $val;
    }
}